package com.t.bricks.bussiness.db.dao.dutyandperson.impl;

import java.util.List;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Repository;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.transaction.interceptor.TransactionAspectSupport;

import com.t.bricks.bussiness.db.dao.dutyandperson.DutyAndPersonDao;
import com.t.bricks.bussiness.db.entity.dutyandperson.DutyAndPerson;
import com.t.bricks.bussiness.db.mapper.dutyandperson.DutyAndPersonMapper;
import com.t.bricks.model.Log;
import com.t.bricks.model.MsgEmity;

@Repository
public class DutyAndPersonDaoImpl implements DutyAndPersonDao<DutyAndPerson> {
	
	@Autowired
	private DutyAndPersonMapper dutyAndPersonMapper;

	/**
	 * 根据人员编号取关联的职务信息
	 * @param sPersonId
	 * @return
	 */
	@Override
	public MsgEmity findBysPersonId(String sPersonId) {
		List<DutyAndPerson> list = null;
		try {
			list = dutyAndPersonMapper.findBysPersonId(sPersonId);
			if (null == list) {
				Log.error("查询数据发生异常,执行的返回值为:null,预期值不应为null");
				return new MsgEmity(false, "查询操作失败！", 7001);
			}
		} catch (Exception e) {
			Log.error("查询数据发生异常:", e.getMessage());
			return new MsgEmity(false, "查询请求失败，请查看异常日志！", 7002);
		}
		
		return new MsgEmity(true, "查询成功！", list);
	}
	
	/**
	 * 批量保存人员所属职务关联信息
	 * 注意:若职务信息为空则会清除所有该人员与职务的关联信息
	 * @param sPersonId 人员编号
	 * @param list 职务与人员关系对象集合
	 * @return
	 */
	@Transactional
	@Override
	public MsgEmity save(String sPersonId, List<DutyAndPerson> list) {
		int iCode = 7002;
		try {
			dutyAndPersonMapper.del(sPersonId);//注意:启用了事务,先删除,然后再添加
			
			if (null == list || list.size() < 1) {
				return new MsgEmity(true, "解除关联成功！", 7999);
			}
			
			int i = dutyAndPersonMapper.save(list);
			if (i < 1) {
				Log.error("关联未能得到预期影响值(预期大于等于1):", i);
				iCode = 7001;
				throw new RuntimeException("关联失败！");
			}
		} catch (Exception e) {
			Log.error("关联时发生异常:", e.getMessage());
			TransactionAspectSupport.currentTransactionStatus().setRollbackOnly();
			return new MsgEmity(false, "关联失败！", iCode);
		}
		
		return new MsgEmity(true, "关联成功！", 7999);
	}
	
	/**
	 * 清除所有该人员与职务的关联信息
	 * @param sPersonId 人员编号
	 * @return
	 */
	@Override
	public MsgEmity del(String sPersonId) {
		try {
			int i = dutyAndPersonMapper.del(sPersonId);
			if (i > 0) {
				return new MsgEmity(true, "删除成功！", 7999);
			}
			
			i = dutyAndPersonMapper.findCountByPerson(sPersonId);
			if (i > 0) {
				return new MsgEmity(false, "删除失败！", 7101);
			}
			
			return new MsgEmity(true, "删除成功，已经没有关联的职务！", 7999);
		} catch (Exception e) {
			Log.error("删除失败：", e.getMessage());
			return new MsgEmity(false, "删除失败，操作数据库异常！", 7102);
		}
	}

}
